//
//  CXUserInfoViewModel.swift
//  Project03-Weibo-swift
//
//  Created by w on 16/1/21.
//  Copyright © 2016年 w. All rights reserved.
//

import UIKit

class CXUserInfoViewModel: NSObject {
    /// 存放用户信息
    var userInfo:CXUserInfo?
    /// 返回授权的access_token
    var accessToken: String? {
        return userInfo?.access_token
    }
    
    var isLogin:Bool {
    /// 将判断是否登录的逻辑写在这里
        if userInfo != nil && isExpire == false {
            return true
        }
        return false
    }
    /// 是否过期
    var isExpire:Bool {
        if NSDate().compare((userInfo?.expireDate)!) == .OrderedAscending {
            return false
        }
        return true
    }
    static let sharedUserModel: CXUserInfoViewModel = {
        //在一开始就加载沙盒的用户信息
        let vm = CXUserInfoViewModel()
        vm.userInfo = vm.userInfoFromSb()
        return vm
    }()
    ///  获取归档路径
    private var archivePath: String{
        let directPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString
        return directPath.stringByAppendingPathComponent("user.plist")
    }
    func loadUserInfo(code: String, completed: (isSuccess: Bool) -> Void) {
        
        //调用自定义封装AFN的方法去请求
        CXNetworkTool.sharedTool.loadUserInfo(code, finished: { (response, error) -> Void in
            if error != nil {
                print("请求获取token出错:\(error)")
                completed(isSuccess: false)
            } else {
                //判断返回的数据是不是指定字典格式
                guard let dict = response as? [String:AnyObject] else {
                    print("返回的字典不是指定格式")
                    completed(isSuccess: false)
                    return
                }
                let user = CXUserInfo(dict: dict)
                //待完善 ..已经拿到Access Token
                //                completed(user, isSuccess: true)
                self.getUserProfile(user, completed: completed)
            }
        })
    }
}
// MARK: - 使用code请求获取授权Token
extension CXUserInfoViewModel {
    private func getUserProfile(user:CXUserInfo,completed: (isSuccess: Bool) -> Void) {
        
        CXNetworkTool.sharedTool.getUserInfo(user.access_token!, uid: user.uid!) { (response, error) -> Void in
            if error != nil {
                print(error)
                completed(isSuccess: false)
            } else {
                print(response)
                
                guard let dict = response as? [String:AnyObject] else {
                    print("返回的字典不是指定格式")
                    completed(isSuccess: false)
                    return
                }
                
                user.avatar_large = dict["avatar_large"] as? String
                user.screen_name = dict["screen_name"] as? String
                print("用户信息出来啦!\(user)")
                self.userInfo = user
                //将用户信息归档
                self.saveUserInfo(user)
                completed(isSuccess: true)
            }

        }        
    }
}
// MARK: - 归解档
extension CXUserInfoViewModel {
    //归档
    private func saveUserInfo(user: CXUserInfo) {
        print(archivePath)
        NSKeyedArchiver.archiveRootObject(user, toFile: archivePath)
    }
    //解档
    func userInfoFromSb() -> CXUserInfo? {
        return NSKeyedUnarchiver.unarchiveObjectWithFile(archivePath) as? CXUserInfo
    }
}